package org.hd.sidemenu.service.impl;

import org.hd.sidemenu.dao.SideMenuDao;
import org.hd.sidemenu.service.SideMenuService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SideMenuServiceImpl implements SideMenuService {

    @Resource
    SideMenuDao sideMenuDao;

    @Override
    public List<Map<String,Object>> getMenus(String username) {

        List<Map<String,String>> result = sideMenuDao.getMenus(username);
        

        List<Map<String,Object>> menuList = new ArrayList<>();
        //值可能是字符串，也可能是数组
        //Map<String,Object> menu = new HashMap<>();
//        中间结果
        Map<String, String> temp = new HashMap<>();

//        二级菜单
        //List<Map<String,String>> childMenu = new ArrayList<>();
        //获取所有的一级菜单
        for(int i=0;i<result.size();i++){
            temp = result.get(i);
//            说明是一级按钮
            if(!temp.containsKey("parent_url")){
                //值可能是字符串，也可能是数组
                Map<String,Object> menu = new HashMap<>();
                //按钮的key值
                menu.put("key",temp.get("url"));
                menu.put("label",temp.get("pdescription"));
                //result.remove(i);
                menu.put("children",new ArrayList<Map<String,String>>());
                menuList.add(menu);
            }
        }
        //temp.clear();
        for(int i=0;i<menuList.size();i++){
            List<Map<String,String>> childMenu = new ArrayList<>();
            for(int j=0;j<result.size();j++){
                if(menuList.get(i).get("key").equals(result.get(j).get("parent_url"))){
                    Map<String,String> t= new HashMap<>();
                    t.put("key",result.get(j).get("url"));
                    t.put("label",result.get(j).get("pdescription"));
                    t.put("onClick",null);
                    childMenu.add(t);
                }
            }
            menuList.get(i).put("children",childMenu);
        }


        return menuList;


    }
}
